package xhwl.insurance.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.Image;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.util.LogUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


import rx.functions.Action1;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.BitmapUtil;
import xhwl.android.common.util.SPUtil;

import de.greenrobot.event.EventBus;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.ToastUtil;

import xhwl.insurance.BaseActivity;
import xhwl.insurance.Constant;
import xhwl.insurance.R;
import xhwl.insurance.adapter.StaffServiceAdapter;
import xhwl.insurance.adapter.VipGridViewAdapter;
import xhwl.insurance.adapter.VipViewPagerAdapter;
import xhwl.insurance.animator.SlideInOutBottomItemAnimator;
import xhwl.insurance.customView.PopSelectPic;
import xhwl.insurance.customView.PullToRefreshView;

import xhwl.insurance.customView.WrapContentLinearLayoutManager;

import xhwl.insurance.event.FreshForumListEvent;

import xhwl.insurance.event.LayoutChangeEvent;
import xhwl.insurance.event.PutQuestionsVoiceEvent;
import xhwl.insurance.event.PutQuestionsVoiceTextEvent;

import xhwl.insurance.http.StaffServiceEvent;
import xhwl.insurance.http.api.ArtificialServiceListApi;

import xhwl.insurance.event.SendVoiceEvent;
import xhwl.insurance.http.api.SendForumApi;
import xhwl.insurance.http.api.SendForumCommentApi;
import xhwl.insurance.http.api.SendVoiceApi;
import xhwl.insurance.http.api.UploadPicApi;
import xhwl.insurance.http.api.UploadVoiceApi;

import xhwl.insurance.http.bean.BottomModelBean;
import xhwl.insurance.http.bean.ImageEvent;
import xhwl.insurance.http.bean.ImageItem;
import xhwl.insurance.http.bean.RecordItem;

import xhwl.insurance.http.bean.resp.CustomerServiceLeftResp;
import xhwl.insurance.http.bean.resp.StaffServiceListResp;
import xhwl.insurance.http.bean.ReferralPicBean;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.insurance.ui.voicesupport.AudioButton;
import xhwl.insurance.ui.voicesupport.MediaPlay;
import xhwl.insurance.util.AndroidBug5497Workaround;
import xhwl.insurance.util.IntentConstants;
import xhwl.insurance.util.KeyBoardUtils;
import xhwl.insurance.util.PermisionUtils;
import xhwl.insurance.util.StringUtil;
import xhwl.insurance.view.AudioButton2;
import xhwl.insurance.view.KeyBoardShowListener;
import xhwl.pulltorefresh.PullToRefreshRecyclerView;
import xhwl.pulltorefresh.callback.PullToRefreshListener;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

import static xhwl.insurance.ui.ImageShowerActivity.EXTRA_IMAGE_URL;


public class StaffServiceActivity extends BaseActivity implements View.OnClickListener,
        PopSelectPic.PopSelectBtnClickListener, PullToRefreshListener {
    private ImageView plus, mic, consult_chat_text;
    private RelativeLayout bottomLayout;
    private PullToRefreshRecyclerView mRecyclerView;
    private static final int TAKE_PICTURE = 1;
    private static final int PICK_PICTURE = 2;
    private int mPage = 1;

    private String path = "";//照相机保存图片路径
    private File fileimg;
    private EditText et;
    private TextView mSend;
    private LinearLayout activityRootView, ll_consult_chat_et, ll_audiobutton;
    private AudioButton2 mAudioButton;
    private RecordItem item;
    private int times;
    private List<StaffServiceListResp> mList = new ArrayList<>();
    private StaffServiceAdapter adapter;
    private int lastIndex = -1;
    private View animeView;
    private View animeView2;
    private int RefreshData = 0;
    private String back_state;
    private ImageView title_left_imageview;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int problem = (int) msg.obj;
            getData(problem);
            super.handleMessage(msg);
        }
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_staff_service);
        AndroidBug5497Workaround.assistActivity(this);
        back_state = getIntent().getStringExtra("BACK_STATE");
    }

    @Override
    public void initViews() {
        initTitleViews();
        plus = (ImageView) findViewById(R.id.consult_chat_plus);
        mic = (ImageView) findViewById(R.id.consult_chat_mic);
        consult_chat_text = (ImageView) findViewById(R.id.consult_chat_text);
        mAudioButton = (AudioButton2) findViewById(R.id.audiobutton_btn);
        bottomLayout = (RelativeLayout) findViewById(R.id.consult_chat_bottomlayout);
        mRecyclerView = (PullToRefreshRecyclerView) findViewById(R.id.RecyclerView);
        et = (EditText) findViewById(R.id.consult_chat_et);
        mSend = (TextView) findViewById(R.id.consult_chat_send);
        activityRootView = (LinearLayout) findViewById(R.id.ll_root_layout);
        ll_consult_chat_et = (LinearLayout) findViewById(R.id.ll_consult_chat_et);
        ll_audiobutton = (LinearLayout) findViewById(R.id.ll_audiobutton);
        title_left_imageview = (ImageView) findViewById(R.id.title_left_imageview);
        initRecylerView();
        initBottomView();
        adapter = new StaffServiceAdapter(StaffServiceActivity.this, mList);
        mRecyclerView.setAdapter(adapter);

        adapter.notifyDataSetChanged();

    }


    private void initRecylerView() {
        //设置EmptyView
        View emptyView = View.inflate(StaffServiceActivity.this, R.layout.layout_empty_view, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        mRecyclerView.setEmptyView(emptyView);

        WrapContentLinearLayoutManager layoutManager =
                new WrapContentLinearLayoutManager(StaffServiceActivity.this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setItemAnimator(new SlideInOutBottomItemAnimator(mRecyclerView));

        //设置是否开启上拉加载
        mRecyclerView.setLoadingMoreEnabled(false);
        //设置是否开启下拉刷新
        mRecyclerView.setPullRefreshEnabled(true);
        //设置是否显示上次刷新的时间
        mRecyclerView.displayLastRefreshTime(false);
//        recyclerView.setRefreshLimitHeight(DimenUtil.dip2px(mActivity,50));
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    }


    /**
     * 发表文本接口
     */
    private void SendText(String sendTextContent) {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        String jg_id = SPUtil.getCommon().getString(SPUtil.Common.JPUSH_ID, "");//极光id
        String talk_type = "text";//文字text；语言voice;图片image;
        String app_key = Constant.JPUSH_APP_KEY;//极光key
        String talk_content = sendTextContent;
        String image_picurl = "";
        String voice_format = "";
        String client_type = Constant.CLIENT_TYPE;
        BaseApi api = new SendVoiceApi(member_id, jg_id, talk_type, app_key, talk_content, image_picurl, voice_format, client_type);
        HttpManager.getInstance().dealHttp(StaffServiceActivity.this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if (resp.isOk()) {
//                    ToastUtil.showToast(StaffServiceActivity.this, "人工客服上传文本成功");
                    //下拉人工客服列表
                    getData(1);
                } else {
                    ToastUtil.showToast(mContext, resp.message);
                }
            }

        });

    }

    /**
     * 发表语音接口
     */
    private void SendVoice(String post_urls) {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        String jg_id = SPUtil.getCommon().getString(SPUtil.Common.JPUSH_ID, "");//极光id
        String talk_type = "voice";//文字text；语言voice;图片image;
        String app_key = Constant.JPUSH_APP_KEY;//极光key
        String talk_content = "";
        String image_picurl = "";
        String voice_format = post_urls;
        String client_type = Constant.CLIENT_TYPE;
        BaseApi api = new SendVoiceApi(member_id, jg_id, talk_type, app_key, talk_content, image_picurl, voice_format, client_type);
        HttpManager.getInstance().dealHttp(StaffServiceActivity.this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if (resp.isOk()) {
                    //下拉人工客服列表
                    RefreshData = 0;
                    getData(1);
                } else {
                    ToastUtil.showToast(mContext, resp.message);
                }
            }

        });
    }

    /**
     * 发表图片接口
     */
    private void sendImage(String imagePath) {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        String jg_id = SPUtil.getCommon().getString(SPUtil.Common.JPUSH_ID, "");//极光id
        String talk_type = "image";//文字text；语言voice;图片image;
        String app_key = Constant.JPUSH_APP_KEY;//极光key
        String talk_content = "";
        String image_picurl = imagePath;
        String voice_format = "";
        String client_type = Constant.CLIENT_TYPE;
        BaseApi api = new SendVoiceApi(member_id, jg_id, talk_type, app_key, talk_content, image_picurl, voice_format, client_type);
        HttpManager.getInstance().dealHttp(StaffServiceActivity.this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if (resp.isOk()) {
                    //下拉人工客服列表
                    mList.clear();
                    getData(1);
                } else {
                    ToastUtil.showToast(mContext, resp.message);
                }
            }

        });

    }


    @Override
    public void onResume() {
        super.onResume();
        MediaPlay.stop();
    }

    @Override
    public void onPause() {
        super.onPause();
        MediaPlay.onPause();
        if (animeView != null) {
            animeView.setBackgroundResource(R.drawable.ic_voice_right03);
        }
        if (animeView2 != null) {
            animeView2.setBackgroundResource(R.drawable.ic_voice_left03);
        }
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("人工客服");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        MediaPlay.onRelease();
        if (mAudioButton != null) {
            mAudioButton.onDestroy();
        }
    }

    @Override
    public void initListener() {
        plus.setOnClickListener(this);
        mic.setOnClickListener(this);
        mSend.setOnClickListener(this);
        consult_chat_text.setOnClickListener(this);
        mRecyclerView.setPullToRefreshListener(this);
        initAdapterItemClickLitener();
        title_left_imageview.setOnClickListener(this);
        mAudioButton.setOnStartListener(new AudioButton.onStartListener() {
            @Override
            public void startRecord() {
                if (animeView != null) {
                    animeView.setBackgroundResource(R.drawable.ic_voice_right03);
                    animeView = null;
                }

                if (animeView2 != null) {
                    animeView2.setBackgroundResource(R.drawable.ic_voice_left03);
                    animeView2 = null;
                }
                MediaPlay.stop();

            }
        });
        mAudioButton.setOnFinishListener(new AudioButton.onFinishListener() {
            @Override
            public void finishRecord(String path, float time) {
                final StaffServiceListResp item = new StaffServiceListResp(path, (int) time);
                //上传语音得到语音地址
                File file = new File(item.getPath());

                //先发送语音得到语音地址
                if (!TextUtils.isEmpty(item.getPath()) && null != item.getPath() && "" != item.getPath()) {
                    UploadVoiceApi api = new UploadVoiceApi(StaffServiceActivity.this, new File[]{file});

                    HttpManager.getInstance().dealHttp(StaffServiceActivity.this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
                        @Override
                        public void onNext(ArrayList<ReferralPicBean> list) {
                            String voiceUrl = list.get(0).getUrl_big();
                            if (null != voiceUrl) {
                                LogUtils.e("LLL1"+voiceUrl);
                                //发表语音接口
                                SendVoice(voiceUrl);
                            }
                        }
                    });
                } else {
                    Toast.makeText(mContext, "发表的语音内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }

        });


        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                bottomLayout.setVisibility(View.GONE);
                return false;
            }
        });


        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView view, int scrollState) {
                // TODO Auto-generated method stub
                switch (scrollState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
//                        adapter.handler.removeCallbacksAndMessages(null);
////                        adapter.notifyDataSetChanged();
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
//                        adapter.handler.removeCallbacksAndMessages(null);
//                        tbAdapter.setIsGif(false);
//                        tbAdapter.isPicRefresh = true;
//                        reset();
                        KeyBoardUtils.hideKeyBoard(StaffServiceActivity.this, et);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });

        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (et.getText().toString().length() > 0) {
                    mSend.setVisibility(View.VISIBLE);
                    bottomLayout.setVisibility(View.GONE);
                    plus.setVisibility(View.GONE);
                } else {
                    mSend.setVisibility(View.GONE);
                    plus.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //监听软键盘的状态
        new KeyBoardShowListener(StaffServiceActivity.this).setKeyboardListener(
                new KeyBoardShowListener.OnKeyboardVisibilityListener() {
                    @Override
                    public void onVisibilityChanged(boolean visible) {
                        if (visible) {
                            //软键盘已弹出
                            bottomLayout.setVisibility(View.GONE);
                        } else {
                            //软键盘未弹出

                        }
                    }
                }, StaffServiceActivity.this);
    }

    @Override
    public void loadData() {
        getData(1);

    }

    @Override
    public void onRefresh() {
        RefreshData = 1;
        if (RefreshData != 1) {
            mList.clear();
            getData(1);
        } else {
            getData(mPage + 1);
        }

    }

    @Override
    public void onLoadMore() {
//        getData(1);
    }

    private void getData(final int page_num) {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        ArtificialServiceListApi api = new ArtificialServiceListApi(member_id, page_num);
        HttpManager.getInstance().dealHttp(StaffServiceActivity.this, api, new OnNextListener<HttpResp<ArrayList<StaffServiceListResp>>>() {
            @Override
            public void onNext(HttpResp<ArrayList<StaffServiceListResp>> resp) {
                if (page_num == 1) {
                    if (resp.isOk()) {
                        if (resp != null && resp.data.size() > 0) {
                            mPage = page_num;
                            addMsg(resp.data);
                        }else {
                            // 如果mList为空 并且是第一次咨询 就添加“已成功为您转接人工客服，亲，很高兴为您服务，请问有什么可以帮助您？”
                                StaffServiceListResp resp2 = new StaffServiceListResp("", 0);
                                resp2.TALK_CONTENT = getString(R.string.staff_service);
                                resp2.USER_ID = "111";
                                resp2.TALK_TYPE = "text";
                                mList.add(resp2);
                        }
                    } else {
                        ToastUtil.showToast(StaffServiceActivity.this, resp.message);
                    }
                } else {
                    if (resp.isOk()) {//下拉刷新操作
                        if (resp.data != null) {
                            mRecyclerView.setRefreshComplete();
                            mPage = page_num;
                            addMsg(resp.data);
                        } else {
                            ToastUtil.showToast(StaffServiceActivity.this, getString(R.string.no_more_data));
                        }
                    } else {
                        mRecyclerView.setRefreshFail();
                    }
                }
            }
        });
    }


    private void initAdapterItemClickLitener() {
        adapter.setOnItemClickLitener(new StaffServiceAdapter.OnItemClickLitener() {


            @Override
            public void onSendVoiceItemClick(int position, View view) {
                //每次开启动画前，先设置为默认状态
                if (animeView != null) {
                    animeView.setBackgroundResource(R.drawable.ic_voice_right03);
                    animeView = null;
                }
                //通过view获取animeView
                animeView = view.findViewById(R.id.v_animes);
                animeView.setBackgroundResource(R.drawable.voice_animation);
                AnimationDrawable ad = (AnimationDrawable) animeView.getBackground();
                ad.start();

                //播放录制的音频
                MediaPlay.playAudio(mList.get(position).getVOICE_FORMAT(), new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        //播放完成，停止动画效果
                        animeView.setBackgroundResource(R.drawable.ic_voice_right03);
                    }
                });

            }

            @Override
            public void onReceiveVoiceItemClick(int position, View view) {
                //每次开启动画前，先设置为默认状态
                if (animeView2 != null) {
                    animeView2.setBackgroundResource(R.drawable.ic_voice_left03);
                    animeView2 = null;
                }
                animeView2 = view.findViewById(R.id.v_anime_rervice);

                //通过view获取animeView
                animeView2.setBackgroundResource(R.drawable.voice_animation2);
                AnimationDrawable ad2 = (AnimationDrawable) animeView2.getBackground();
                ad2.start();
                //播放录制的音频
                MediaPlay.playAudio(mList.get(position).getVOICE_FORMAT(), new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        //播放完成，停止动画效果
                        animeView2.setBackgroundResource(R.drawable.ic_voice_left03);
                    }
                });

            }

            @Override//点击发送图片详情
            public void onSendPictureDetailsClick(int position, View view) {
                startActivity(new Intent(StaffServiceActivity.this, ImageShowerActivity.class)
                        .putExtra(EXTRA_IMAGE_URL, mList.get(position).getIMAGE_PICURL())
                        .putExtra("type", "5"));
            }

            @Override //点击接收图片详情
            public void onReceivePictureDetailsClick(int position, View view) {
                startActivity(new Intent(StaffServiceActivity.this, ImageShowerActivity.class)
                        .putExtra(EXTRA_IMAGE_URL, mList.get(position).getIMAGE_PICURL())
                        .putExtra("type", "5"));
            }

        });

    }

    public void onEvent(SendVoiceEvent event) {
        if (animeView != null) {
            animeView.setBackgroundResource(R.drawable.ic_voice_right03);
            animeView = null;
        }
        if (animeView2 != null) {
            animeView2.setBackgroundResource(R.drawable.ic_voice_left03);
            animeView2 = null;
        }
        MediaPlay.stop();

    }

    private void addMsg(ArrayList<StaffServiceListResp> bean) {
            if (RefreshData != 1) {//访问接口添加数据
                mList.clear();
                StaffServiceListResp resp = new StaffServiceListResp("", 0);
                resp.TALK_CONTENT = getString(R.string.staff_service);
                resp.USER_ID = "111";
                resp.TALK_TYPE = "text";
                mList.add(resp);
                mList.addAll(bean);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRecyclerView.smoothScrollToPosition(mList.size());
                    }
                }, 200);//需要延迟scroll
                LogUtils.e("KKK访问接口添加数据:"+RefreshData);
                adapter.notifyDataSetChanged();
            } else {   //添加下拉刷新的数据
                mList.addAll(0, bean);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mList.size() > 10) {
                            mRecyclerView.smoothScrollToPosition(-mList.size() + 1);
                        } else {
                            mRecyclerView.smoothScrollToPosition(mList.size() + 1);
                        }
                    }
                }, 400);//需要延迟scroll
                LogUtils.e("KKK添加下拉刷新的数据:"+RefreshData);
                adapter.notifyDataSetChanged();
            }
    }

    public void onEvent(LayoutChangeEvent event) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRecyclerView.smoothScrollToPosition(mList.size());
            }
        }, 200);//需要延迟scroll
        adapter.notifyDataSetChanged();
    }


    public void onEvent(Object obj) {
        if (obj == null)
            return;
        if (obj instanceof ImageEvent) {
            ImageEvent event = (ImageEvent) obj;
            Collection<ImageItem> collection = event.getCollection();
            List<File> list = new ArrayList<>();
            for (ImageItem item : collection) {// 目前只能选择一张图片，可上传多张图片时，需根据接口定义修改s
                Bitmap bitmap = BitmapUtil.compressImage(item.getSourcePath());
                fileimg = new File(item.getSourcePath());
                if (fileimg != null && fileimg.exists()) {
                    list.add(fileimg);
                }
                    uploadPic(list);
            }
        }
    }

    public void onEvent(StaffServiceEvent event) {
        RefreshData = 0;
        getData(1);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case TAKE_PICTURE:
                List<File> list = new ArrayList<>();
                ImageItem item = new ImageItem();
                item.sourcePath = path;
                fileimg = new File(item.sourcePath);

                if (fileimg != null && fileimg.exists()) {
                    list.add(fileimg);
                }
                uploadPic(list);
                break;
        }
    }

    private void uploadPic(final List<File> fileList) {
        if (fileList == null || fileList.size() == 0)
            return;

        final UploadPicApi api = new UploadPicApi(StaffServiceActivity.this, true, fileList.toArray(new File[fileList.size()]));
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onNext(ArrayList<ReferralPicBean> picBeanList) {
                api.hideDialog();
                StringBuilder sb = new StringBuilder();
                for (ReferralPicBean bean : picBeanList) {
                    sb.append(bean.getUrl_big());
                }
                sendImage(sb.toString());
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                api.hideDialog();
            }
        });
    }


    @Override
    protected boolean handleETTouchEvent() {
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.consult_chat_plus://点击“+”
                mic.setVisibility(View.VISIBLE);
                ll_consult_chat_et.setVisibility(View.VISIBLE);
                consult_chat_text.setVisibility(View.GONE);
                ll_audiobutton.setVisibility(View.GONE);

                if (hideBottomView()) {
                    bottomLayout.setVisibility(View.VISIBLE);
                    KeyBoardUtils.hideKeyBoard(StaffServiceActivity.this, et);
                } else {
                    bottomLayout.setVisibility(View.GONE);
                    KeyBoardUtils.showKeyBoard(StaffServiceActivity.this, et);
                }
                break;
            case R.id.consult_chat_send: //点击发送
//                KeyBoardUtils.showKeyBoard(StaffServiceActivity.this, et);
                String voiceUrl = "";
                String sendContent = et.getText().toString();
                if (xhwl.android.common.util.StringUtil.isEmpty(sendContent)) {
                    ToastUtil.showToast(mContext, "发送内容不能为空！");
                    return;
                }
                SendText(sendContent);
                et.setText("");
                break;
            case R.id.consult_chat_mic://语音
                KeyBoardUtils.hideKeyBoard(StaffServiceActivity.this, et);
                consult_chat_text.setVisibility(View.VISIBLE);
                mic.setVisibility(View.GONE);
                ll_consult_chat_et.setVisibility(View.GONE);
                ll_audiobutton.setVisibility(View.VISIBLE);
                bottomLayout.setVisibility(View.GONE);
                break;

            case R.id.consult_chat_text://文字
                consult_chat_text.setVisibility(View.GONE);
                ll_consult_chat_et.setVisibility(View.VISIBLE);
                ll_audiobutton.setVisibility(View.GONE);
                mic.setVisibility(View.VISIBLE);
                KeyBoardUtils.hideKeyBoard(StaffServiceActivity.this, et);
                bottomLayout.setVisibility(View.GONE);
                break;
            case R.id.title_left_imageview://
                if (back_state.equals("1")) {
                    startActivity(new Intent(StaffServiceActivity.this, CustomerServiceActivity.class)
                            .putExtra("BACK_STATE", "1"));
                    finish();
                } else {
                    finish();
                }
                break;

        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (bottomLayout != null && bottomLayout.getVisibility() == View.VISIBLE) {
            if (!StringUtil.isEmpty(et.getText().toString())) {
                bottomLayout.setVisibility(View.VISIBLE);
            } else {
                bottomLayout.setVisibility(View.GONE);
            }
        }
        return super.onTouchEvent(event);
    }

    public boolean hideBottomView() {
        if (bottomLayout != null && bottomLayout.getVisibility() == View.VISIBLE) {
            bottomLayout.setVisibility(View.GONE);
            return false;
        }
        return true;
    }


    int pageSize = 1;

    //点击加号出现的布局
    public void initBottomView() {
        ViewPager mPager = (ViewPager) findViewById(R.id.consult_chat_viewpager);
//		LinearLayout mLlDot = (LinearLayout) findViewById(R.id.ll_dot);

        // 初始化数据源
        ArrayList<BottomModelBean> mDatas = getBottomDatas();
        LayoutInflater inflater = LayoutInflater.from(this);
        // 总的页数=总数/每页数量，并取整
        int pageCount = (int) Math.ceil(mDatas.size() * 1.0 / pageSize);
        ArrayList<View> mPagerList = new ArrayList<View>();
        for (int i = 0; i < pageCount; i++) {
            // 每个页面都是inflate出一个新实例
            final GridView gridView = (GridView) inflater.inflate(R.layout.gridview,
                    mPager, false);
            gridView.setAdapter(new VipGridViewAdapter(this, mDatas, i,
                    pageSize));
            mPagerList.add(gridView);
            // 设置适配器
            mPager.setAdapter(new VipViewPagerAdapter(mPagerList));
            //0-图片
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    bottomLayout.setVisibility(View.GONE);
                    switch (arg2) {
                        case 0:
                            PopSelectPic pop = new PopSelectPic(StaffServiceActivity.this, gridView);
                            pop.setCallBack(StaffServiceActivity.this);
                            break;

                        default:
                            break;
                    }
                }
            });
        }
    }

    /**
     * 初始化数据源
     */
    private ArrayList<BottomModelBean> getBottomDatas() {
        ArrayList<BottomModelBean> mDatas = new ArrayList<BottomModelBean>();
        String[] titles = {"图片", "视频", "语音"};
        int[] imgs = {R.drawable.consult_img,
                R.drawable.consult_img, R.drawable.consult_img};
        for (int i = 0; i < titles.length; i++) {
            // 动态获取资源ID，第一个参数是资源名，第二个参数是资源类型例如drawable，string等，第三个参数包名
            int imageId = getResources().getIdentifier("ic_category_" + i,
                    "mipmap", getPackageName());
            mDatas.add(new BottomModelBean(titles[i], imgs[i]));
        }
        return mDatas;
    }

    @Override
    public void onTakePhotoClick() {
        takePhoto();
    }

    @Override
    public void onSelectPicClick() {
        pickPicture();
    }

    public void takePhoto() {

        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
                    if (!vFile.exists()) {
                        File vDirPath = vFile.getParentFile();
                        vDirPath.mkdirs();
                    } else {
                        if (vFile.exists()) {
                            vFile.delete();
                        }
                    }
                    path = vFile.getPath();
                    Uri cameraUri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        cameraUri = FileProvider.getUriForFile(getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
                    } else {
                        cameraUri = Uri.fromFile(vFile);
                    }
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);

                } else {
                    LogUtils.e("请打开提示对应权限,否则将影响拍照功能无法使用");
                    PermisionUtils.dialog(StaffServiceActivity.this, "请打开提示对应权限,否则将影响拍照功能无法使用");
                }
            }
        });
    }

    public void pickPicture() {
        Intent intent = new Intent(mContext,
                ImageBucketChooseActivity.class);
        intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE,
                1);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (back_state.equals("1")) {
                startActivity(new Intent(StaffServiceActivity.this, CustomerServiceActivity.class)
                        .putExtra("BACK_STATE", "1"));
                finish();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
